<?php

namespace App\Service\Friend;

use App\Constants\ErrorCode;
use App\Model\UserProfile;
use App\Service\BaseService;

/**
 * 匹配一个用户
 */
class MatchOneService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $userProfile = UserProfile::getProfile($userId);

        if ($userProfile->gender != 1 && $userProfile->gender != 0) {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '你还未设置资料性别,暂无法使用改功能');
        }

        //获取新手指定的主播
        $matchUserId = $this->getMatchId($userId, $userProfile->gender);
        if (!$matchUserId) {
            return $this->setError(ErrorCode::NO_VALID_HOST, '当前声优均在忙碌中，请稍后再试~');
        }
        //查询用户资料
        $userInfo = UserProfile::buildHostItem(UserProfile::getProfile($matchUserId));
        log_user_result($userId, $userInfo);
        return [
            'user_info' => $userInfo
        ];
    }

    /**
     * 获取匹配主播ID
     */
    function getMatchId($userId, $userGender = 1)
    {
        //推荐异性
        $hostIds = UserProfile::getNewUsers(UserProfile::ROLE_USER, 1 - $userGender);
        if (empty($hostIds)) return 0;
        return $hostIds[array_rand($hostIds)];
    }
}
